const Redis = require("koa-redis");
const { redis } = require("../../dbs/config");
const nodemailer = require("nodemailer");
const Email = require("../../dbs/config");
const User = require("../../dbs/models/user");
const axios = require("../utils/axios");
const passport = require("../utils/passport");
const Store = new Redis({
  port: redis.port,
  host: redis.host,
  password: redis.password
}).client;

module.exports = {
  get signup() {
    return async ctx => {
      // 前端需要传递username, password, comfirmpsw, email, code
      // 结构
      const { username, password, email, code, comfirmpsw } = ctx.request.body;
      if (
        !(
          username &&
          password &&
          email &&
          code &&
          comfirmpsw &&
          password == comfirmpsw
        )
      ) {
        return (ctx.body = {
          code: -1,
          msg: "请输入正确信息"
        });
      }
      /* 
  1. 检验验证码是否存在并且是否过期
  2. 校验该用户名是否已经存在
  */

      if (code) {
        let saveCode = await Store.hget(`nodemail:${username}`, "code");
        if (saveCode) {
          if (saveCode.toLowerCase() !== code.toLowerCase()) {
            return (ctx.body = {
              code: -1,
              msg: "请输入正确的验证码"
            });
          }
        } else {
          return (ctx.body = {
            code: -1,
            msg: "验证码已过期，请重新尝试"
          });
        }
      } else {
        return (ctx.body = {
          code: -1,
          msg: "请填写验证码"
        });
      }
      let user = await User.find({ username });
      if (user.length > 0) {
        return (ctx.body = {
          code: -1,
          msg: "该用户已存在"
        });
      }
      let nuser = await User.create({ username, password, email });
      if (nuser) {
        // 自动登录
        let res = await axios.post("/users/signin", { username, password });
        let cookie = res.headers["set-cookie"];
        if (res.data.code === 0 && res.status === 200) {
          // 开启session, 自动登录功能
          ctx.response.set("set-cookie", cookie);
          return (ctx.body = {
            code: 0,
            msg: "注册成功"
          });
        }
      }
      return (ctx.body = {
        code: -1,
        msg: "注册失败"
      });
    };
  },

  get signin() {
    return async ctx => {
      return passport.authenticate("local", (err, user, info) => {
        if (err) {
          return (ctx.body = {
            code: -1,
            msg: info
          });
        }
        if (!user) {
          return (ctx.body = {
            code: -1,
            msg: info
          });
        }
        let { weekSign } = ctx.request.body;
        ctx.body = {
          code: 0,
          msg: info,
          user: {
            id: user._id,
            username: user.username,
            email: user.email,
            createTime: user.createTime
          }
        };
        if (typeof eval(weekSign) == "boolean" && weekSign) {
          ctx.session.maxAge = 1000 * 60 * 20;
          ctx.session.passport = { user: user._id };
          return;
        } else {
          return ctx.login(user);
        }
      })(ctx);
    };
  },

  get verify() {
    return async ctx => {
      let { username } = ctx.request.body;
      let saveCode = await Store.hget(`nodemail:${username}`, "code");
      if (saveCode) {
        return (ctx.body = {
          code: -1,
          msg: "验证请求过于频繁，请一分钟后重试"
        });
      }
      // smtp服务配置 参考文档 https://nodemailer.com/smtp/
      let transporter = nodemailer.createTransport({
        host: Email.smtp.host,
        secure: false,
        auth: {
          user: Email.smtp.user,
          pass: Email.smtp.pass
        }
      });
      // 接受者信息
      let ko = {
        code: Email.smtp.code(),
        email: ctx.request.body.email,
        user: ctx.request.body.username
      };
      // 邮件配置
      let mailOptions = {
        from: `"不打酱油组" <${Email.smtp.user}>`,
        to: ko.email,
        subject: "仿美团实战验证码",
        html: `您在不打酱油组之项目实战仿美团网中注册，您的验证码是${ko.code}`
      };
      // 发送邮件
      await transporter.sendMail(mailOptions);
      // 存储验证码
      let result = await Store.hmset(`nodemail:${ko.user}`, {
        code: ko.code,
        email: ko.email
      });
      if (result.toLowerCase() === "ok") {
        Store.expire(`nodemail:${ko.user}`, 60);
      }
      return (ctx.body = {
        code: 0,
        msg: "验证码发送成功, 有效期为1分钟"
      });
    };
  }
};
